package cn.shadow.module;

import cn.shadow.moulde.AModule;
import cn.shadow.moulde.Module;
import cn.shadow.moulde.ModuleHub;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 实现ApplicationContextAware接口，可以将获得applicationContext对象
 * 通过applicationContext对象可以拿到所有相同注解的对象
 */
@Service
public class ModuleList implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    private List<Module> getAllModule() {
        Map<String, Object> beansWithAnnotationMap =
                applicationContext.
                        getBeansWithAnnotation(AModule.class);
        List<Module> modules = new ArrayList<>();
        for (Object value : beansWithAnnotationMap.values()) {
            if (value instanceof Module) {
                Module module = (Module) value;
                modules.add(module);
            }
        }
        return modules;
    }

    /**
     * 所有模块对象
     */
    @Bean
    public ModuleHub moduleHub() {
        return ModuleHub.newModuleHub(getAllModule());
    }

    /**
     * 这个是在所有对象都初始化完成之后
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(AModule.class);
        System.out.println(beans);
    }
}
